<script setup lang="ts">
  import { reactive, ref } from 'vue'
  import { createSubCategoryReq } from '@/api'
  import { message } from 'ant-design-vue'

  const props = defineProps(['columnData0', 'parentCatId'])
  interface FormState {
    level: string
    title: string
    parent: string
  }

  const formState = reactive<FormState>({
    level: '0',
    title: '',
    parent: '',
  })

  const formRef = ref()

  const showCreate = defineModel()

  const levelChange = (value: string) => {
    formState.level = value
  }

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(async () => {
        const { parent, ...dataObj } = formState
        const parentCatId = props.parentCatId
        let res
        if (formState.level === '0') {
          res = await createSubCategoryReq({ ...dataObj, parentCatId })
        } else {
          res = await createSubCategoryReq({
            ...dataObj,
            parentId: parent,
            parentCatId,
          })
        }
        if (res?.data) {
          message.success('分类创建成功')
          showCreate.value = false
        } else {
          message.error('分类创建失败')
        }
      })
      .catch(() => {})
  }
</script>

<template>
  <a-form
    ref="formRef"
    :model="formState"
    name="createCategoryForm"
    style="padding: 20px"
  >
    <a-form-item
      name="level"
      label="级别"
      :validate-trigger="['']"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
    >
      <a-select
        ref="select"
        v-model:value="formState.level"
        style="width: 120px"
        @change="levelChange"
      >
        <a-select-option value="0">一级分类</a-select-option>
        <a-select-option
          value="1"
          v-if="columnData0?.length > 0"
          >二级分类</a-select-option
        >
      </a-select>
    </a-form-item>

    <a-form-item
      name="title"
      label="名称"
      :validate-trigger="['']"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
      :rules="[{ required: true, message: '名称不能为空' }]"
    >
      <a-input v-model:value.trim="formState.title" />
    </a-form-item>

    <a-form-item
      name="parent"
      label="上级分类"
      v-if="formState.level === '1'"
      :rules="[{ required: true, message: '上级分类不能为空' }]"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
    >
      <a-select
        v-model:value="formState.parent"
        style="width: 200px"
      >
        <a-select-option
          v-for="item in columnData0"
          :key="item.id"
          :value="item.id"
          >{{ item.title }}</a-select-option
        >
      </a-select>
    </a-form-item>

    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button
        type="primary"
        style="width: 200px; height: 40px"
        @click="onSubmit"
        >提交</a-button
      >
    </a-form-item>
  </a-form>
</template>

<style scoped lang="less"></style>
